from pub.routine import UdpClient, UdpServer
from pub.routine import TcpClient, TcpServer
from pub.routine import ZmqClient, ZmqServer

TplServer = TcpServer
TplClient = TcpClient

from .protocal import SayHelloTrans

RCP_PORT = 31615
APP_DESC = "SayHello, a test of rcp-protocal [v0.2.0] 2019/11/03"

def run_client():
    from time import sleep

    def getopt():
        import argparse
        parser = argparse.ArgumentParser("sayHello", description=APP_DESC)
        parser.add_argument("ipaddr", action="store", help="远程服务端IP地址")
        return parser.parse_args()

    args = getopt()
    print("IP address: ", args.ipaddr)

    client = TplClient((args.ipaddr, RCP_PORT))
    protocal = SayHelloTrans()
    client.set_protocal(protocal)

    def break_cmd_loop():
        # client.stop()  # RuntimeError: cannot join current thread
        client.sock.close()
        print(">> Socket结束运行，请输入任意键退出程序")

    client.listen(break_cmd_loop)

    # 发送默认命令
    protocal.command()

    try:
        waitForCmd = True
        while waitForCmd:
            data = input("Input the Data ([Q] for quit): ")
            if data == "Q":
                client.stop()  # 关闭监听
                break
            else:
                protocal.request(data)
    except Exception:
        print("正在终止当前进程...")

    client.stop()
    print("End")


def run_server():
    server = TplServer(RCP_PORT)
    protocal = SayHelloTrans()
    server.set_protocal(protocal)
    server.listen()

    while True:
        data = input("[Q] for quit: ")
        if data == "Q":
            server.stop()  # 关闭监听
            break

    print("End")
